#include <string>

using namespace std;

class Solution {
public:
    string longestPalindrome(string s) {
        if (s.length() < 2) return s;
        int start = 0, maxLen = 0;
        int len = s.length();
        for (int i=0; i<len;) {
            if (len - i <= maxLen/2) break;  // 剩余子串长度不够
            int left = i, right = i;
            // 过滤重复
            while (right < len - 1 && s[right] == s[right+1]) ++right;
            i = right + 1; // 下次在判断的时候从重复的下一个字符开始判断
            while (right < len - 1 && left > 0 && s[left-1] == s[right+1]) {
                ++right;
                --left;
            }
            // 保留最长
            if (right - left + 1 > maxLen) {
                start = left;
                maxLen = right - left + 1;
            }
        }
        return s.substr(start, start + maxLen);
    }
};
